import type { Plugin, ViteDevServer } from 'vite';
import { ProgressTrackingPluginOptions, ModuleStats } from './types';
import { readFileSync } from 'fs';
import { resolve } from 'path';

// Read CSS and JS files directly instead of using import with query parameters
const progressStyle = readFileSync(resolve(__dirname, './client/progress-style.css'), 'utf-8');
const progressScript = readFileSync(resolve(__dirname, './client/progress-script.js'), 'utf-8');

export function progressTrackingPlugin(options: ProgressTrackingPluginOptions = {}): Plugin {
  let server: ViteDevServer | undefined;
  const moduleStats: ModuleStats = {
    total: 0,
    processed: 0,
    pending: new Set()
  };
  
  // 处理用户配置选项，设置默认值
  const {
    color = '#646cff',
    height = 3,
    showStatus = true
  } = options;
  
  // 替换CSS中的默认值为用户配置
  const customStyle = progressStyle
    .replace('#646cff', color)
    .replace('height: 3px', `height: ${height}px`)
    .replace(showStatus ? '' : '#vite-progress-status { display: none !important; }', 
             !showStatus ? '#vite-progress-status { display: none !important; }' : '');

  return {
    name: 'progress-tracking',
    apply: 'serve',
    enforce: 'pre',
    
    configureServer(_server) {
      server = _server;
    },
    
    async transform(code, id) {
      if (server && id) {
        moduleStats.total++;
        moduleStats.pending.add(id);

        server.ws.send('progress:update', {
          total: moduleStats.total,
          processed: moduleStats.processed,
          current: id
        });

        await server.waitForRequestsIdle(id);

        moduleStats.processed++;
        moduleStats.pending.delete(id);

        server.ws.send('progress:update', {
          total: moduleStats.total,
          processed: moduleStats.processed,
          current: null
        });
      }
      return code;
    },
    
    transformIndexHtml: {
      order: 'pre',
      handler(html) {
        return {
          html,
          tags: [
            {
              tag: 'style',
              children: customStyle,
              injectTo: 'head'
            },
            {
              tag: 'div',
              attrs: { id: 'vite-progress-bar' },
              injectTo: 'body-prepend'
            },
            {
              tag: 'div',
              attrs: { id: 'vite-progress-status' },
              children: 'Loading...',
              injectTo: 'body-prepend'
            },
            {
              tag: 'script',
              attrs: { type: 'module' },
              children: progressScript,
              injectTo: 'body'
            }
          ]
        };
      }
    }
  };
}
